package com.rabbit.springrabbitmq.message;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.support.converter.MessageConversionException;
import org.springframework.amqp.support.converter.MessageConverter;


/**
 * @Author: JohnCoding
 * @Description:  自定义的消息转换类
 * @date: 2020/8/6 23:11
 */
public class TextMessageConverter implements MessageConverter {
    /**
     * Java对象转换Message对象
     * @param o
     * @param messageProperties
     * @return
     * @throws MessageConversionException
     */
    @Override
    public Message toMessage(Object o, MessageProperties messageProperties) throws MessageConversionException {
        return new Message(o.toString().getBytes(),messageProperties);
    }

    /**
     * Message转Java对象
     * @param message
     * @return
     * @throws MessageConversionException
     */
    @Override
    public Object fromMessage(Message message) throws MessageConversionException {
        Object contentType = message.getMessageProperties().getHeaders().get("contentType");
        if(null != contentType && contentType.toString().contains("text")){
            return new String(message.getBody());
        }
        return message.getBody();
    }
}
